var ctx=window.daijia.ctx;
var address=window.daijia.address;
var iserrand=window.daijia.iserrand;
var allmap2=null;//跑腿地图对象
var map2=null;
var driving=null;
var driving3=null;
var distance=null;
var timeStr=null;
var start = new Array();
var end = new Array();
var addressPoint = new Array();
var orderType=null;//订单类型 id
var areaId=null;//类型对应的收费id
var endAdd=null;//目的地是否选填
var areaWeightId = null;//重量收费id
var otherService = "";//附加服务
function initialize2(){
	var myGeo = new BMap.Geocoder();
	
	myGeo.getPoint(address, function(point){
		if (point) {
			map2 = new BMap.Map("allmap2");  
			map2.centerAndZoom(point, 13);
			map2.enableScrollWheelZoom();
			//BMAP_DRIVING_POLICY_LEAST_TIME：最少时间，默认
			//BMAP_DRIVING_POLICY_LEAST_DISTANCE：最短距离
			//BMAP_DRIVING_POLICY_AVOID_HIGHWAYS：避开高速
			driving = new BMap.DrivingRoute(map2, {
				policy : BMAP_DRIVING_POLICY_LEAST_DISTANCE,
				onSearchComplete: function(results){   
					if (driving.getStatus() == BMAP_STATUS_SUCCESS){ 
					 // 获取第一条方案   
					 var plan = results.getPlan(0); 
					 distance=plan.getDistance();
					 timeStr=plan.getDuration(); 
					 $.post(ctx+"/errand/up/getPrice",
						   {areaId:areaId,
						 	areaWeightId:areaWeightId,
						 	weight:$("#weight").val(),
						 	thanksCash:$("#thanksCash").val(),
							goodsCash:$("#goodsCash").val(),
							protectPrice:$("#protectPrice").val(),
							couponId:$("#errand_couponId").val(),
						    time:timeStr,
						    mileage:distance},function(data){							    	
						    	$("#shouldPay").val(data.money);
						    	$("#startPrice").val(data.startPrice);
						    	$("#mileagePrice").val(data.mileagePrice);
						    	$("#travelTimePrice").val(data.travelTimePrice);
						    	$("#travelTime").val(data.travelTime);
						    	$("#mileage").val(data.mileage);
						    	$("#weightPrice").val(data.weightPrice);
						    	$(".mileage_text").text("预计路程:"+data.mileage+"公里");
						    	$(".travelTime_text").text("预计时间:"+data.travelTime+"分钟");
						    },"json");
					 
					}
				},
				renderOptions: {    //显示到地图上
					map: map2,    
					autoViewport: true 
				}  
			});
			 
		    //右键菜单
		    var contextMenu = new BMap.ContextMenu();    
			var txtMenuItem = [{
				text:'设为任务起点',
				callback:function(p){
					if(null == areaId || null == areaWeightId){
						$.scojs_message("该公司没有开通此类型，不能下单", $.scojs_message.TYPE_ERROR);
						return;
					}
					map2.clearOverlays();				   		
			   		var memberMarker = new BMap.Marker(p);  // 创建标注
			   		map2.addOverlay(memberMarker);
		    			
	    			var gc = new BMap.Geocoder();
				    gc.getLocation(p, function(rs){
				        var addComp = rs.addressComponents;
				        if(addComp.street+addComp.streetNumber != ""){
				        	$("#startAddress").val(addComp.street+" "+addComp.streetNumber);
				        }else{
				        	$("#startAddress").val("");
				        	$.scojs_message("起点地址获取失败，请填写起点,手动定位", $.scojs_message.TYPE_ERROR);
				        }
				        $("#startAddress").attr("lng",p.lng);
				        $("#startAddress").attr("lat",p.lat);
				        $.post(ctx+"/errand/up/getPrice",
								   {areaId:areaId,
				        			areaWeightId:areaWeightId,
				        			weight:$("#weight").val(),
				        			thanksCash:$("#thanksCash").val(),
									goodsCash:$("#goodsCash").val(),
									protectPrice:$("#protectPrice").val(),
									couponId:$("#errand_couponId").val(),
								    time:timeStr,
								    mileage:distance},function(data){							    	
								    	$("#shouldPay").val(data.money);
								    	$("#startPrice").val(data.startPrice);
								    	$("#mileagePrice").val(data.mileagePrice);
								    	$("#travelTimePrice").val(data.travelTimePrice);
								    	$("#travelTime").val(data.travelTime);
								    	$("#mileage").val(data.mileage);
								    	$("#weightPrice").val(data.weightPrice);
										$(".mileage_text").text("预计路程:"+data.mileage+"公里");
										$(".travelTime_text").text("预计时间:"+data.travelTime+"分钟");
								    },"json");
				        start[0]=p.lng;
				        start[1]=p.lat;
				        var point=new BMap.Point(p.lng,p.lat);
			    	    addressPoint[0]= point;
				    	   
				        if(addressPoint.length>1){
			    		    map2.centerAndZoom(addressPoint[0], 10);
							driving.search(addressPoint[0], addressPoint[1]);
				        }
				        $("#detailedAddress").val("");
				        if(rs.surroundingPois[0].title.trim()!=null && rs.surroundingPois[0].title.trim()!=""){
			        	   $("#detailedAddress").val(rs.surroundingPois[0].title);
				        }
				    });
			    }
			},{
			   text:'设为任务终点',
			   callback:function(p){
				   if(null == areaId || null == areaWeightId){
						$.scojs_message("该公司没有开通此类型，不能下单", $.scojs_message.TYPE_ERROR);
						return;
					}
				   map2.clearOverlays();
				   
				   var memberMarker = new BMap.Marker(p);  // 创建标注
				   map2.addOverlay(memberMarker);
				   
				   var gc = new BMap.Geocoder();
				   gc.getLocation(p, function(rs){
					   var addComp = rs.addressComponents;
					   if(addComp.street+addComp.streetNumber != ""){
				        	$("#deliverAddress").val(addComp.street+" "+addComp.streetNumber);
				        }else{
				        	$("#deliverAddress").val("");
				        	$.scojs_message("终点地址获取失败，请填写终点，手动定位", $.scojs_message.TYPE_ERROR);
				        }
					   $("#deliverLng").val(p.lng);
					   $("#deliverLat").val(p.lat);
					   $("#deliverAddress").attr("lng",p.lng);
					   $("#deliverAddress").attr("lat",p.lat);
					   end[0]=p.lng;
					   end[1]=p.lat;
					   var point=new BMap.Point(p.lng,p.lat);
			    	   addressPoint[1]= point;
			    	   if(addressPoint.length>1){
			    		    map2.centerAndZoom(addressPoint[0], 10);
							driving.search(addressPoint[0], addressPoint[1]);
				       }
					   $("#deliverDetailedAddress").val("");
					   if(rs.surroundingPois[0].title.trim()!=null && rs.surroundingPois[0].title.trim()!=""){
						   
					   }
				   });
			   }
			}];
			
			for(var i=0; i < txtMenuItem.length; i++){
				contextMenu.addItem(new BMap.MenuItem(txtMenuItem[i].text,txtMenuItem[i].callback,100));
				if(i==1 || i==3) {
					contextMenu.addSeparator();
				}
			}
			map2.addContextMenu(contextMenu); 
			
			
		}else{
			$.scojs_message("地区"+address+"位置不准确,请重新编辑地区", $.scojs_message.TYPE_ERROR);
		}
	});
	
}

$(document).ready(function(){
	if(iserrand=="errand"){
		initialize2();
		$.get(ctx+"/errand/up/orderTypeList",{'companyId':$("#companyId2").val()},function(data){
			var text="";
			var otherServices = "";
			if(data==null||data.length==0){
				text="当前公司没有跑腿类型";
				$(".startAddress").text("任务起点");
				$(".deliverAddress").text("任务终点");
				orderType=null;
				areaId=null;
				endAdd=null;
				areaWeightId=null;
			}else{
				for(var i=0;i<data.length;i++){
					if(i==0){
						text+="<li class='active orderTypeItem' otherServices='"+JSON.stringify(data[i].otherServices)+"' errandValuationMethod='"+data[i].errandValuationMethod+"' startHint='"+data[i].startHint+"' endHint='"+data[i].endHint+"' endAddress='"+data[i].endAddress+"' areaId='"+data[i].areaId+"'><a data-toggle='tab' class='navigation' type='"+data[i].id+"'>"+data[i].typeName+"</a></li>";
						var starthint = data[i].startHint;
						var endhint = data[i].endHint
						$(".startAddress").text(starthint==null||starthint==""?"任务起点":starthint);
						$(".deliverAddress").text(endhint==null||endhint==""?"任务终点":endhint);
						orderType=data[i].id;
						areaId=data[i].areaId;
						areaWeightId=data[i].areaWeightId;
						endAdd=data[i].endAddress;
						if(data[i].errandValuationMethod!=true){
				    		$("#valuationType").text("定价金额");
				    	}else{
				    		$("#valuationType").text("打表金额");
				    	}
						otherService = "";
						if(data[i].otherServices != "" && data[i].otherServices.length >0){
							for (var int = 0; int < data[i].otherServices.length; int++) {
								otherService += data[i].otherServices[int].id + ",";
								otherServices += "<label><input type='checkbox' name='otherServices' value='" + data[i].otherServices[int].id +"'/>"+ data[i].otherServices[int].otherServices +"</label>&nbsp;&nbsp;&nbsp;&nbsp;";
							}
						}
						$("#addServices").html(otherServices);
						
					}else{
						text+="<li  class='orderTypeItem' otherServices='"+JSON.stringify(data[i].otherServices)+"' errandValuationMethod='"+data[i].errandValuationMethod+"' startHint='"+data[i].startHint+"' endHint='"+data[i].endHint+"' endAddress='"+data[i].endAddress+"' areaId='"+data[i].areaId+"'><a data-toggle='tab' class='navigation' type='"+data[i].id+"'>"+data[i].typeName+"</a></li>";
					}
				}
			}
			
			$("#title").html(text);
		},"json")
	}
	
	$("#errandClick").click(function(){
		$("#companyId2").change();
		initialize2();
	});
	
	
	$("#passengerPhone").change(function(){
		if(null == areaId || null == areaWeightId){
			$.scojs_message("该公司没有开通此类型，不能下单", $.scojs_message.TYPE_ERROR);
			return;
		}
		var company = $("#companyId2").val();
		$.get(ctx+'/member/findByPhone',{'phone':$("#passengerPhone").val(),'couponType':'paotui','couponTypeId':orderType},function(data){
			if(data.passenger!=null){
				$("#companyName").val(data.passenger.companyName);
				$("#passengerId").val(data.passenger.id);
				$("#passengerName").val(data.passenger.name);
				$("#clientVirtual2").text(data.passenger.drawMoney+data.passenger.nodrawMoney+"元");
				if(data.passenger.inBlackList){
					$("#membertype2").html("黑名单");
				}else{
					$("#membertype2").html(data.passenger.typeStr);
				}
				
				if(data.coupons!=null&&data.coupons.length>0){
					var text="<option value=''>"+"请选择优惠券"+"</option>";
					for(var i=0;i<data.coupons.length;i++){
						text+= "<option value='"+data.coupons[i].id+"'>"+data.coupons[i].couponRule.title+"</option>";
					}
					$("#errand_couponId").empty();
					if(text!=""){
						$("#errand_couponInput").css("display","block");
						$("#errand_couponId").append(text);
					}
					
				}else{
					$("#errand_couponInput").css("display","none");
					$("#errand_couponId").empty();
				}
				$("#companyId2 option").each(function(index,element){
				  	if($(element).attr("value")==data.passenger.companyId){
				 		$(element).attr("selected","selected");
				 		return false;
				 	}
				});
			}else{
				$("#errand_couponInput").css("display","none");
				$("#errand_couponId").empty();
				$("#membertype2").html("新客户");
				$("#passengerName").val("先生/女士");
			}
			if(company!=$("#companyId2").val())
			$("#companyId2").change();
		});
	});
	
	$("#endPhone").val($("#passengerPhone").val());			
		
	if($("#deliverLng").val()!=""&&$("#deliverLat").val()!=""&&$("#startLng")&&$("#startLat")){
		if(null == areaId || null == areaWeightId){
			$.scojs_message("该公司没有开通此类型，不能下单", $.scojs_message.TYPE_ERROR);
			return;
		}
		 $.post(ctx+"/errand/up/getPrice",{
			 passengerId:$('#passengerId').val(),
			 companyId:$("#companyId2").val(),
			 areaWeightId:areaWeightId,
			 weight:$("#weight").val(),
			 couponId:$("#errand_couponId").val(),
			 time:timeStr,
			 mileage:distance
			 },function(data){
			 $("#shouldPay").val(data.money);
			 $("#startPrice").val(data.startPrice);
			 $("#mileagePrice").val(data.mileagePrice);
			 $("#travelTimePrice").val(data.travelTimePrice);
			 $("#travelTime").val(data.travelTime);
			 $("#mileage").val(data.mileage);
			 $(".mileage_text").text("预计路程:"+data.mileage+"公里");
			 $(".travelTime_text").text("预计时间:"+data.travelTime+"分钟");
	    },"json");
	}
	
	$("#weight").change(function(){
		if(null == areaId || null == areaWeightId){
			$.scojs_message("该公司没有开通此类型，不能下单", $.scojs_message.TYPE_ERROR);
			return;
		}
		$.post(ctx+"/errand/up/getPrice",
				   {areaId:areaId,
					areaWeightId:areaWeightId,
					weight:$("#weight").val(),
					thanksCash:$("#thanksCash").val(),
					goodsCash:$("#goodsCash").val(),
					protectPrice:$("#protectPrice").val(),
					couponId:$("#errand_couponId").val(),
				    time:timeStr,
				    mileage:distance},function(data){							    	
				    	$("#shouldPay").val(data.money);
				    	$("#startPrice").val(data.startPrice);
				    	$("#mileagePrice").val(data.mileagePrice);
				    	$("#travelTimePrice").val(data.travelTimePrice);
				    	$("#travelTime").val(data.travelTime);
				    	$("#weightPrice").val(data.weightPrice);
				    	$("#mileage").val(data.mileage);
						$(".mileage_text").text("预计路程:"+data.mileage+"公里");
						$(".travelTime_text").text("预计时间:"+data.travelTime+"分钟");
				    },"json");
	});
	
	$("#errand_couponId").change(function(){
		if(null == areaId || null == areaWeightId){
			$.scojs_message("该公司没有开通此类型，不能下单", $.scojs_message.TYPE_ERROR);
			return;
		}
		$.post(ctx+"/errand/up/getPrice",
				   {areaId:areaId,
					areaWeightId:areaWeightId,
					weight:$("#weight").val(),
					thanksCash:$("#thanksCash").val(),
					goodsCash:$("#goodsCash").val(),
					protectPrice:$("#protectPrice").val(),
					couponId:$("#errand_couponId").val(),
				    time:timeStr,
				    mileage:distance},function(data){							    	
				    	$("#shouldPay").val(data.money);
				    	$("#startPrice").val(data.startPrice);
				    	$("#mileagePrice").val(data.mileagePrice);
				    	$("#travelTimePrice").val(data.travelTimePrice);
				    	$("#travelTime").val(data.travelTime);
				    	$("#weightPrice").val(data.weightPrice);
				    	$("#mileage").val(data.mileage);
						$(".mileage_text").text("预计路程:"+data.mileage+"公里");
						$(".travelTime_text").text("预计时间:"+data.travelTime+"分钟");
				    },"json");
	});
	
	$("#thanksCash").change(function(){
		if(null == areaId || null == areaWeightId){
			$.scojs_message("该公司没有开通此类型，不能下单", $.scojs_message.TYPE_ERROR);
			return;
		}
		$.post(ctx+"/errand/up/getPrice",
				   {areaId:areaId,
					areaWeightId:areaWeightId,
					weight:$("#weight").val(),
					thanksCash:$("#thanksCash").val(),
					goodsCash:$("#goodsCash").val(),
					protectPrice:$("#protectPrice").val(),
					couponId:$("#errand_couponId").val(),
				    time:timeStr,
				    mileage:distance},function(data){							    	
				    	$("#shouldPay").val(data.money);
				    	$("#startPrice").val(data.startPrice);
				    	$("#mileagePrice").val(data.mileagePrice);
				    	$("#travelTimePrice").val(data.travelTimePrice);
				    	$("#travelTime").val(data.travelTime);
				    	$("#weightPrice").val(data.weightPrice);
				    	$("#mileage").val(data.mileage);
						$(".mileage_text").text("预计路程:"+data.mileage+"公里");
						$(".travelTime_text").text("预计时间:"+data.travelTime+"分钟");
				    },"json");
	});
	
	$("#goodsCash").change(function(){
		if(null == areaId || null == areaWeightId){
			$.scojs_message("该公司没有开通此类型，不能下单", $.scojs_message.TYPE_ERROR);
			return;
		}
		$.post(ctx+"/errand/up/getPrice",
				   {areaId:areaId,
					areaWeightId:areaWeightId,
					weight:$("#weight").val(),
					thanksCash:$("#thanksCash").val(),
					goodsCash:$("#goodsCash").val(),
					protectPrice:$("#protectPrice").val(),
					couponId:$("#errand_couponId").val(),
				    time:timeStr,
				    mileage:distance},function(data){							    	
				    	$("#shouldPay").val(data.money);
				    	$("#startPrice").val(data.startPrice);
				    	$("#mileagePrice").val(data.mileagePrice);
				    	$("#travelTimePrice").val(data.travelTimePrice);
				    	$("#travelTime").val(data.travelTime);
				    	$("#weightPrice").val(data.weightPrice);
				    	$("#mileage").val(data.mileage);
						$(".mileage_text").text("预计路程:"+data.mileage+"公里");
						$(".travelTime_text").text("预计时间:"+data.travelTime+"分钟");
				    },"json");
	});
	
	$("#protectPrice").change(function(){
		if(null == areaId || null == areaWeightId){
			$.scojs_message("该公司没有开通此类型，不能下单", $.scojs_message.TYPE_ERROR);
			return;
		}
		$.post(ctx+"/errand/up/getPrice",
				   {areaId:areaId,
					areaWeightId:areaWeightId,
					weight:$("#weight").val(),
					thanksCash:$("#thanksCash").val(),
					goodsCash:$("#goodsCash").val(),
					protectPrice:$("#protectPrice").val(),
					couponId:$("#errand_couponId").val(),
				    time:timeStr,
				    mileage:distance},function(data){							    	
				    	$("#shouldPay").val(data.money);
				    	$("#startPrice").val(data.startPrice);
				    	$("#mileagePrice").val(data.mileagePrice);
				    	$("#travelTimePrice").val(data.travelTimePrice);
				    	$("#travelTime").val(data.travelTime);
				    	$("#weightPrice").val(data.weightPrice);
				    	$("#mileage").val(data.mileage);
						$(".mileage_text").text("预计路程:"+data.mileage+"公里");
						$(".travelTime_text").text("预计时间:"+data.travelTime+"分钟");
				    },"json");
	});
	
	$("#companyId2").change(function(){
		$.get(ctx+"/errand/up/orderTypeList",{'companyId':$(this).val()},function(data){
			var text="";
			if(data==null||data.length==0){
				text="当前公司没有跑腿类型";
				$(".startAddress").text("任务起点");
				$(".deliverAddress").text("任务终点");
				orderType=null;
				areaId=null;
				endAdd=null;
			}else{
				for(var i=0;i<data.length;i++){
					if(i==0){
						text+="<li class='active orderTypeItem' otherServices='"+JSON.stringify(data[i].otherServices)+"' errandValuationMethod='"+data[i].errandValuationMethod+"' startHint='"+data[i].startHint+"' endHint='"+data[i].endHint+"' endAddress='"+data[i].endAddress+"' areaId='"+data[i].areaId+"'><a data-toggle='tab' class='navigation' type='"+data[i].id+"'>"+data[i].typeName+"</a></li>";
						var starthint = data[i].startHint;
						var endhint = data[i].endHint
						$(".startAddress").text(starthint==null||starthint==""?"任务起点":starthint);
						$(".deliverAddress").text(endhint==null||endhint==""?"任务起点":endhint);
						orderType=data[i].id;
						areaId=data[i].areaId;
						endAdd=data[i].endAddress;
						if(data[i].errandValuationMethod!=true){
				    		$("#valuationType").text("定价金额");
				    	}else{
				    		$("#valuationType").text("打表金额");
				    	}
					}else{
						text+="<li  class='orderTypeItem' otherServices='"+JSON.stringify(data[i].otherServices)+"' errandValuationMethod='"+data[i].errandValuationMethod+"' startHint='"+data[i].startHint+"' endHint='"+data[i].endHint+"' endAddress='"+data[i].endAddress+"' areaId='"+data[i].areaId+"'><a data-toggle='tab' class='navigation' type='"+data[i].id+"'>"+data[i].typeName+"</a></li>";
					}
				}
			}
			
			$("#title").html(text);
			 $.post(ctx+"/errand/up/getPrice",
					   {areaId:areaId,
				 		areaWeightId:areaWeightId,
				 		weight:$("#weight").val(),
				 		thanksCash:$("#thanksCash").val(),
						goodsCash:$("#goodsCash").val(),
						protectPrice:$("#protectPrice").val(),
						couponId:$("#errand_couponId").val(),
					    time:timeStr,
					    mileage:distance},function(data){							    	
					    	$("#shouldPay").val(data.money);
					    	$("#startPrice").val(data.startPrice);
					    	$("#mileagePrice").val(data.mileagePrice);
					    	$("#travelTimePrice").val(data.travelTimePrice);
					    	$("#travelTime").val(data.travelTime);
					    	$("#mileage").val(data.mileage);
					    	$("#weightPrice").val(data.weightPrice);
							$(".mileage_text").text("预计路程:"+data.mileage+"公里");
							$(".travelTime_text").text("预计时间:"+data.travelTime+"分钟");
					    },"json");
		},"json")
		
		
		
	});
	
	$("#errandCreate").click(function(){
		$("#errandCreate").attr("disabled","disabled");
		if(null == areaId || null == areaWeightId){
			$.scojs_message("该公司没有开通此类型，不能下单", $.scojs_message.TYPE_ERROR);
			$("#errandCreate").removeAttr("disabled");
			return;
		}
		type=orderType;
		if(orderType==null){
			$.scojs_message("请选择订单类型", $.scojs_message.TYPE_ERROR);
			$("#errandCreate").removeAttr("disabled");
			return;
		}
		if($("#content").val().trim()==''){
			$.scojs_message("请填写任务内容", $.scojs_message.TYPE_ERROR);
			$("#errandCreate").removeAttr("disabled");
			return;
		}
		
		if($("#content").val().length>200){
			$.scojs_message("任务内容应小于200字", $.scojs_message.TYPE_ERROR);
			$("#errandCreate").removeAttr("disabled");
			return;
		}
		if(endAdd){
			if($("#deliverAddress").val()==''){
				$.scojs_message("请填写交付地点", $.scojs_message.TYPE_ERROR);
				$("#errandCreate").removeAttr("disabled");
				return;
			}
		}
		
		if($("#passengerPhone").val()==''){
			$.scojs_message("请填写客户电话", $.scojs_message.TYPE_ERROR);
			$("#errandCreate").removeAttr("disabled");
			return;
		}
		
		if($("#passengerName").val()==''){
			$.scojs_message("请填写客户姓名", $.scojs_message.TYPE_ERROR);
			$("#errandCreate").removeAttr("disabled");
			return;
		}
		if($("#companyId2").val()==''){
			$.scojs_message("请选择公司", $.scojs_message.TYPE_ERROR);
			$("#errandCreate").removeAttr("disabled");
			return;
		}
		/**if($("#goodsCash").val()==""){
			$.scojs_message("请填写商品金额", $.scojs_message.TYPE_ERROR);
			$("#errandCreate").removeAttr("disabled");
			return;
		}
		if($("#weight").val()==""){
			$.scojs_message("请填写商品重量", $.scojs_message.TYPE_ERROR);
			$("#errandCreate").removeAttr("disabled");
			return;
		}
		if($("#thanksCash").val()==""){
			$.scojs_message("请填写感谢费用金额", $.scojs_message.TYPE_ERROR);
			$("#errandCreate").removeAttr("disabled");
			return;
		}
		if($("#protectPrice").val()==""){
			$.scojs_message("请填写保价金额", $.scojs_message.TYPE_ERROR);
			$("#errandCreate").removeAttr("disabled");
			return;
		}*/
		var begin=new Date($('#startTime').val().replace(/-/g,"/"));
	   	if(begin.getTime()-new Date().getTime()<0){
	   		$('#startTime').val(new Date(new Date().getTime()+1000*60*3).Format("yyyy-MM-dd hh:mm"));
	    }
		
		var startAddress;
		startAddress= $("#startAddress").val();	
		var deliverAddress;
		deliverAddress = $("#deliverAddress").val();
		if(startAddress=="" && deliverAddress==""){
			$.scojs_message("起点和终点请至少填写一项", $.scojs_message.TYPE_ERROR);
			$("#errandCreate").removeAttr("disabled");
			return;
		}
		/**if($("#startAddress").attr("lat")=="" && $("#deliverAddress").attr("lat")==""){
			$.scojs_message("起点和终点请至少填写一项", $.scojs_message.TYPE_ERROR);
			$("#errandCreate").removeAttr("disabled");
			return;
		}*/
		if($("#shouldPay").val()==""){
			$.scojs_message("请填写预算金额", $.scojs_message.TYPE_ERROR);
			$("#errandCreate").removeAttr("disabled");
			return;
		}
		else if($("#shouldPay").val()!=""){
			var moneyReg=/^(\d+)(.[0-9]{0,1})?$/;
			if(!moneyReg.test($("#shouldPay").val())){
				$.scojs_message("预算金额格式不正确,例:12.5", $.scojs_message.TYPE_ERROR);
				$("#errandCreate").removeAttr("disabled");
				return;
			}
		}
		
		if($("#shouldPay").val()>10000){
			$.scojs_message("订单价格超出限制，最高10000", $.scojs_message.TYPE_ERROR);
			$("#errandCreate").removeAttr("disabled");
			return;
		}
		var otherServices = "";
		if(otherService != ""){
		   $("input[name=otherServices]:checked").each(function(index,element){
				otherServices += $(element).val() + ",";
			});
	/**	   if(otherServices.length <= 1){
			   $.scojs_message("请选择附加服务", $.scojs_message.TYPE_ERROR);
			   $("#errandCreate").removeAttr("disabled");
				return;
		   }*/
		}
		$.ajax({
             type: "POST",
             url: ctx+"/errand/up/create",
             data: {
            	 passengerId:$("#passengerId").val(),
            	 passengerName:$("#passengerName").val(),
            	 passengerPhone:$("#passengerPhone").val(),
            	 companyId:$("#companyId2").val(),
            	 startAddress:startAddress,
            	 startDetailed:$("#startDetailedAddress").val(),
            	 startLat:$("#startAddress").attr("lat"),
				 startLng:$("#startAddress").attr("lng"),
				 content:$("#content").val(),
				 startTime:$("#startTime").val(),
            	 deliverAddress:deliverAddress,
            	 endDetailed:$("#deliverDetailedAddress").val(),
            	 deliverLat:$("#deliverAddress").attr("lat"),
            	 deliverLng:$("#deliverAddress").attr("lng"),
            	 orderTypeId:type,
				 imgs:$("#imgsUrl").val(),
            	 startPrice:$("#startPrice").val(),
            	 mileagePrice:$("#mileagePrice").val(),
            	 travelTimePrice:$("#travelTimePrice").val(),
            	 travelTime:$("#travelTime").val(),
            	 mileage:$("#mileage").val(),
//            	 companyName:$("#companyName").val(),
            	 shouldPay:$("#shouldPay").val(),
            	 goodsCash:$("#goodsCash").val(),
            	 thanksCash:$("#thanksCash").val(),
            	 protectPrice:$("#protectPrice").val(),
            	 weight:$("#weight").val(),
            	 weightPrice:$("#weightPrice").val(),
            	 otherServices:otherServices,
            	 couponId:$("#errand_couponId").val()
             },	
             dataType: "json",
             success: function(data){
            	 if(data.success){
            		 $.scojs_message("下单成功", $.scojs_message.TYPE_OK);
//            		 window.opener.location.reload(true);
            		 setTimeout(function(){
	            		 window.close();
	     				},500);
            	 }else{
            		 $.scojs_message("跑腿下单失败", $.scojs_message.TYPE_ERROR);
            		 $("#errandCreate").removeAttr("disabled");
            		 return;
            	 }
             }
         });
		
		 issubmit=true;
		  
	});
	
	$("li[specify=false]").click(function(){
		$("#startLat").val("");
		$("#startLng").val("");
		$("#startAddress").val("");
		$("#detailedAddress").val("");
		start = new Array();
	});
	
	//定位
	$(".btn-deliverAddress").click(function(){
		var input =  $(this).parent().parent().find("input");
		
		var str = $(this).parent().parent().find("input").val();
		
		if(str==''){
			$.scojs_message("请填写地址", $.scojs_message.TYPE_ERROR);
		}else{
			map2.clearOverlays();
			var local = new BMap.LocalSearch(map2, {
				renderOptions:{map: map2, autoViewport:true}
			});
			local.search(str);
			
			local.setInfoHtmlSetCallback(function(poi,html){
	    	   
	    	   input.attr("lng",poi.marker.point.lng);
	    	   input.attr("lat",poi.marker.point.lat);
	    	   var i = input.attr("index");
	    	   var point=new BMap.Point(poi.marker.point.lng,poi.marker.point.lat);
	    	   addressPoint[i]= point;
	    	   
		       var markers = map2.getOverlays();
			   for(var i=0;i<markers.length;i++){
					markers[i].show();
			   }
		       if(addressPoint.length>1){
					driving.search(addressPoint[0], addressPoint[1]);
					poi.marker.hide(); 
		       }
		    });
		}
	});
	
	//自动补全交付地点
	$("#deliverAddress").AutoComplete({
	    data: ctx+"/order/getHistoryInputedPlace",
		ajaxDataType: "json",
	    itemHeight: 24,
	    width:"auto",
	    async: true,
	    listStyle: "custom",
	    emphasis: false,
	    matchHandler: function(keyword, data){
	        return true;
	    },
	    createItemHandler: function(index, data){
	    	if(data.address.length>14){
        		return "<span title='"+data.address+"'>"+data.address.substring(0,14)+"</span>";
        	}
            return "<span title='"+data.address+"'>"+data.address+"</span>";
	    },
	    afterSelectedHandler: function(data){
	    	var address = (data.address).split(" ");
	    	$("#deliverAddress").val(address[0]);
	    	$("#deliverDetailedAddress").val(address[1]);
	    	$("#deliverLat").val(data.latitude);
	    	$("#deliverLng").val(data.longitude);
	    	if($("#startAddress").val()!=""){
				var startPoint=new BMap.Point(parseFloat($("#startLng").val()),parseFloat($("#startLat").val()));
				var endPoint=new BMap.Point(parseFloat($("#deliverLng").val()),parseFloat($("#deliverLat").val()));
				map2.centerAndZoom(startPoint, 10); 
				driving.search(startPoint, endPoint);
			}	
	    	 var p = new BMap.Point(data.longitude,data.latitude);
			    var marker = new BMap.Marker(p); 
			    map2.addOverlay(marker);
	        markerComplete(data.longitude,data.latitude);
	    }
	}).AutoComplete('show');
	
	var inputC;
	$(".autoComplete").focus(function(){
		inputC = $(this);
		$(".autoComplete").AutoComplete({
		    data: ctx+"/order/getHistoryInputedPlace",
			ajaxDataType: "json",
		    itemHeight: 24,
		    max:1,
		    width: "auto",
		    async: true,
		    listStyle: "custom",
		    emphasis: false,
		    matchHandler: function(keyword, data){
		        return true;
		    },
		    createItemHandler: function(index, data){
		    	if(data.address.length>14){
	        		return "<span title='"+data.address+"'>"+data.address.substring(0,14)+"</span>";
	        	}
	            return "<span title='"+data.address+"'>"+data.address+"</span>";
		    },
		    afterSelectedHandler: function(data){
		    	var address = (data.address).split(" ");
		    	
		    	inputC.val(data.address);
		    	var i = inputC.attr("index");
		        var p = new BMap.Point(data.longitude,data.latitude);
		        inputC.attr("lng",data.longitude);
		        inputC.attr("lat",data.latitude);
		        addressPoint[i]=p;
			    var marker = new BMap.Marker(p); 
			    if(addressPoint.length==1){
					 $.post(ctx+"/errand/up/getPrice",
						   {areaId:areaId,
						 	areaWeightId:areaWeightId,
						 	weight:$("#weight").val(),
						 	thanksCash:$("#thanksCash").val(),
							goodsCash:$("#goodsCash").val(),
							protectPrice:$("#protectPrice").val(),
							couponId:$("#errand_couponId").val(),
						    time:"",
						    mileage:""},function(data){	
						    	$("#shouldPay").val(data.money);
						    	$("#startPrice").val(data.startPrice);
						    	$("#mileagePrice").val(data.mileagePrice);
						    	$("#travelTimePrice").val(data.travelTimePrice);
						    	$("#travelTime").val(data.travelTime);
						    	$("#mileage").val(data.mileage);
						    	$("#weightPrice").val(data.weightPrice);
						    	$(".mileage_text").text("预计路程:"+data.mileage+"公里");
						    	$(".travelTime_text").text("预计时间:"+data.travelTime+"分钟");
						    },"json");
			    }
			    if(addressPoint.length>1){
					driving.search(addressPoint[0], addressPoint[1]);
					
		        }else{
		        	 map2.addOverlay(marker);
				     markerComplete(data.longitude,data.latitude);
		        }
			   
		    }
		}).AutoComplete('show');
	});
	
	//切换类型
	var flag = false;
    $(document).on("click",".orderTypeItem",function(){
       var li = $(this);
	   var endAddress =  li.attr("endAddress");
	   var endhint = li.attr("endhint");
	   var type = li.children("a").attr("type")
	   var starthint = li.attr("starthint");
	   var addService = eval(li.attr("otherServices"));
	   var otherServices = "";
	   otherService = "";
	   if(addService != "" && addService.length >0){
			for (var int = 0; int < addService.length; int++) {
				otherService += addService[int].id + ",";
				otherServices += "<label><input type='checkbox' name='otherServices' value='" + addService[int].id +"'/>"+ addService[int].otherServices +"</label>&nbsp;&nbsp;&nbsp;&nbsp;";
			}
		}
	   $("#addServices").html("");
	   $("#addServices").html(otherServices);
	   areaId=li.attr("areaid");
		$(".startAddress").text(starthint==null||starthint==""||starthint=="null"? "任务起点":starthint);
		$(".deliverAddress").text(endhint==null||endhint==""||endhint=='null'? "任务终点":endhint);
		orderType=type;
		 $.post(ctx+"/errand/up/getPrice",
				   {areaId:areaId,
			 		areaWeightId:areaWeightId,
			 		weight:$("#weight").val(),
			 		thanksCash:$("#thanksCash").val(),
					goodsCash:$("#goodsCash").val(),
					protectPrice:$("#protectPrice").val(),
					couponId:$("#errand_couponId").val(),
				    time:timeStr,
				    mileage:distance},function(data){							    	
				    	$("#shouldPay").val(data.money);
				    	$("#startPrice").val(data.startPrice);
				    	$("#mileagePrice").val(data.mileagePrice);
				    	$("#travelTimePrice").val(data.travelTimePrice);
				    	$("#travelTime").val(data.travelTime);
				    	$("#mileage").val(data.mileage);
				    	$("#weightPrice").val(data.weightPrice);
				    	if(li.attr("errandValuationMethod")!="true"){
				    		$("#valuationType").text("定价金额");
				    	}else{
				    		$("#valuationType").text("打表金额");
				    	}
				    	
				    	$(".mileage_text").text("预计路程:"+data.mileage+"公里");
				    	$(".travelTime_text").text("预计时间:"+data.travelTime+"分钟");
				    },"json");
		 $.get(ctx+'/member/findByPhone',{'phone':$("#passengerPhone").val(),'couponType':'paotui','couponTypeId':orderType},function(data){
				if(data.passenger!=null){
					$("#companyName").val(data.passenger.companyName);
					$("#passengerId").val(data.passenger.id);
					$("#passengerName").val(data.passenger.name);
					$("#clientVirtual2").text(data.passenger.drawMoney+data.passenger.nodrawMoney+"元");
					if(data.passenger.inBlackList){
						$("#membertype2").html("黑名单");
					}else{
						$("#membertype2").html(data.passenger.typeStr);
					}
					
					if(data.coupons!=null&&data.coupons.length>0){
						var text="<option value=''>"+"请选择优惠券"+"</option>";
						for(var i=0;i<data.coupons.length;i++){
							text+= "<option value='"+data.coupons[i].id+"'>"+data.coupons[i].couponRule.title+"</option>";
						}
						$("#errand_couponId").empty();
						if(text!=""){
							$("#errand_couponInput").css("display","block");
							$("#errand_couponId").append(text);
						}
						
					}else{
						$("#errand_couponInput").css("display","none");
						$("#errand_couponId").empty();
					}
					$("#companyId2 option").each(function(index,element){
					  	if($(element).attr("value")==data.passenger.companyId){
					 		$(element).attr("selected","selected");
					 		return false;
					 	}
					});
				}else{
					$("#errand_couponInput").css("display","none");
					$("#errand_couponId").empty();
					$("#membertype2").html("新客户");
					$("#passengerName").val("先生/女士");
				}
			});
    });
	
	//图片上传
	$("#shareImage_btn").click(function(){
		var imgCount = $("#imgs").children("img").length;		
		if(imgCount<=4){
			$("#shareImage_file").click();			
		}
	});
	$("#deleteImg").click(function(){
		var imgCount = $("#imgs").children("img").length;
		if(imgCount>0){
			var imgs = $("#imgs").children("img");
			$(imgs.get(imgs.length-1)).remove();
			$.scojs_message("删除成功", $.scojs_message.TYPE_OK);
			$("#shareImage_btn").css("display","block");
			var paths =  $("#imgsUrl").val().split(",");
			var newpath = new Array();
			for(var i=0;i<paths.length-1;i++){				
				newpath[i]=paths[i];
			}
			$("#imgsUrl").val(newpath.toString());
		}			
	});
	
	$(document).on('change','#shareImage_file',function(){
		if($.trim($(this).val())){
		 	$.ajaxFileUpload({
                url:ctx+'/common/uploaderrandimg',
                secureuri:false,
                fileElementId:'shareImage_file',
                dataType: 'json',
                success: function (data) {

                	if(data.success){
                		$.scojs_message("上传成功", $.scojs_message.TYPE_OK);
                    	
                		$("#imgs").append("<img class='img' style='margin:3px 0 0 3px;' src="+ctx+"/"+data.minurl+"></img>");
                	   
                		if($("#imgsUrl").val()==""){
                			
                			$("#imgsUrl").val(data.url+"-"+data.minurl)
               		
                		}else{
                			var path = $("#imgsUrl").val();
                			
                			$("#imgsUrl").val(path+","+data.url+"-"+data.minurl);
                			
                		}     		
                		var imgCount = $("#imgs").children("img").length;
                		if(imgCount==5){
                			$("#shareImage_btn").css("display","none");			
                		}
                		
                	}else{
                		$.scojs_message(result.msg, $.scojs_message.TYPE_ERROR);
                	}
                }
            });
		}
	});
});

Date.prototype.Format = function(fmt) 
{ 
  var o = { 
    "M+" : this.getMonth()+1,                 //月份 
    "d+" : this.getDate(),                    //日 
    "h+" : this.getHours(),                   //小时 
    "m+" : this.getMinutes(),                 //分 
    "s+" : this.getSeconds(),                 //秒 
    "q+" : Math.floor((this.getMonth()+3)/3), //季度 
    "S"  : this.getMilliseconds()             //毫秒 
  }; 
  if(/(y+)/.test(fmt)) 
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
  for(var k in o) 
    if(new RegExp("("+ k +")").test(fmt)) 
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
  return fmt; 
}
